# gbconv control program file.
# Grown by LiuZhiyan.
# http://lzy.javaeye.com/
# lzy.dev@gmail.com

require 'win32/process' # Windows platform-dependent. You can remove this require file on *nix platform directly.

require 'gbconv_comm.rb'

begin
	# Open and read pid file but not close for hold it until program exit.
	@pid = File.open(pid_filepath).read.to_i
rescue
	@pid = nil
end

def running
	begin
		# Check process is running.
		return Process.kill(0, @pid) ? true : false
		
		# This is for *nix platform.
		# return (Process.kill(0, @pid) == 1)
	rescue
		return false
	end
end

def start
	return puts "#{APP_NAME} is running." if running
	
	print "Starting #{APP_NAME}..."

	# Process::create come from "win32/process" extension.
	# It used to replace "system" call to create deamon process on windows platform.
	# system("ruby #{workdir_path}/gbconvd.rbw")
	Process::create({ :app_name => "ruby '#{workdir_path}/gbconvd.rbw'", :creation_flags => Process::CREATE_NEW_PROCESS_GROUP | Process::CREATE_NO_WINDOW, :startup_info => { :sw_flags => Windows::Window::SW_HIDE } })

	puts "done."
end

def stop
	return unless running
	
	print "Stopping #{APP_NAME}..."

	# SIGHUP signal unsuppourted on windows platform.
	# Use SIGHUP on *nix, but SIGINT(signal 2) on windows platform.

	# Error: SIGINT(signal 2) not work finely. See http://lzy.javaeye.com/blog/283469 posting.
	# Process::kill(2, @pid)# if running
	Process::kill(9, @pid) if running # Kill deamon process directly.

	# Waiting for deamon process exit.
	sleep(0.1) while running
	
	puts "done."
end

def status()
	puts "#{APP_NAME} is #{running ? "running" : "stopped" }."
end	

case ARGV.first
	when 'status':
		status
	when 'start':
		start
	when 'stop':
		stop
	when 'restart':
		stop
		start
end

unless %w{start stop restart status}.include? ARGV.first
	puts "Usage: #{APP_NAME} {start|stop|restart|status}"
        exit
end
